package movie.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import movie.dao.BaseDao;
import movie.dao.MovieDao;
import movie.entity.Movie;


public class MovieDaoImpl extends BaseDao implements MovieDao{

	public boolean addMovie(Movie movie) {
		String sql = "INSERT INTO movie VALUES (0,?,?,?);";
		this.openConnection();
		ArrayList list = new ArrayList();
		int rows = 0;
		list.add(movie.getTitle());
		list.add(movie.getDirector());
		list.add(movie.getDateReleased());
		try {
			rows = this.excuteUpdate(sql, list.toArray());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			this.closeConnection();
		}
		return rows>0;
	}

	public List<Movie> showMovieList() {
		List<Movie> list = new ArrayList<Movie>();
		this.openConnection();
		String sql = "select * from movie";
		ResultSet rs = null;
		try {
			rs = this.excuteQuery(sql, null);
			while(rs.next()){
				int id = rs.getInt("id");
				String title = rs.getString("title");
				String director = rs.getString("director");
				String dateReleased = rs.getString("datereleased");
				Movie m = new Movie(id, title, director, dateReleased);
				list.add(m);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			this.closeConnection();
		}
		return list;
	}
	
	public static void main(String[] args) {
		for(Movie m : new MovieDaoImpl().showMovieListByName("西")){
			System.out.println(m.getId()+"\t"+m.getTitle());
		}
	}

	public List<Movie> showMovieListByName(String name) {
		List<Movie> list = new ArrayList<Movie>();
		this.openConnection();
		String sql = "select * from movie where title like ?";
		ResultSet rs = null;
		try {
			rs = this.excuteQuery(sql, new Object[]{"%"+name+"%"});
			while(rs.next()){
				int id = rs.getInt("id");
				String title = rs.getString("title");
				String director = rs.getString("director");
				String dateReleased = rs.getString("datereleased");
				Movie m = new Movie(id, title, director, dateReleased);
				list.add(m);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			this.closeConnection();
		}
		return list;
	}


}
